﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// Provides services for managing <see cref="Customer"/> entities, including operations for handling associated
/// collections and attachments.
/// </summary>
/// <remarks>This service extends <see cref="DataWithCollectionAndAttachmentService{TDbContext, TEntity,
/// TCollection}"/> to include additional functionality specific to <see cref="Customer"/> entities and their related
/// <see cref="CustomerContact"/> collections. It also integrates with a variety of dependencies, such as logging,
/// caching, HTTP context access, and file services.</remarks>
/// <typeparam name="TDbContext">The type of the database context used by the service. Must derive from <see cref="DbContext"/>.</typeparam>
/// <param name="logger"></param>
/// <param name="context"></param>
/// <param name="cache"></param>
/// <param name="httpContextAccessor"></param>
/// <param name="fileService"></param>
/// <param name="httpSetting"></param>
/// <param name="dataWithCollectionService"></param>
/// <param name="personalService"></param>
public class CustomerService<TDbContext>(
    ILogger<CustomerService<TDbContext>> logger,
    TDbContext context,
    IDistributedCache cache,
    IHttpContextAccessor httpContextAccessor,
    IFileService fileService,
    IDataWithCollectionService<TDbContext, Customer, CustomerContact> dataWithCollectionService,
    PersonalService<TDbContext> personalService,
    HttpSetting httpSetting) :
    DataWithCollectionAndAttachmentService<TDbContext, Customer, CustomerContact>(logger, context, cache, httpContextAccessor, fileService, httpSetting, dataWithCollectionService),
    IDataWithCollectionAndAttachmentService<TDbContext, Customer, CustomerContact>
    where TDbContext : DbContext
{
    protected readonly PersonalService<TDbContext> _personalService = personalService;

    /// <summary>
    /// 重写的内部新增方法, 在新增 <see cref="Customer"/> 实体时，确保其关联的 <see cref="CustomerContact"/> 中的 <see cref="Contact"/> 实体也被添加到数据库上下文中。
    /// </summary>
    /// <param name="entitySet"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    protected override async Task InternalAddAsync(Customer entitySet, DataServiceContext? context = null)
    {
        if (entitySet.Contacts != null && entitySet.Contacts.Count > 0)
        {
            context ??= new DataServiceContext();
            context.AutoSaveChanges = false;

            // Ensure that the contacts are added to the database context
            foreach (var contact in entitySet.Contacts)
            {
                if (contact.Contact is not null)
                {
                    await _personalService.AddAsync(contact.Contact, context);
                }
            }
        }

        await base.InternalAddAsync(entitySet, context);
    }
}